// pages/detail/detail.js
const { getArtworkDetailsById,downloadArtwork,updateUserLikeStatus,shareArtwork } = require("../../../utils/request");
const config = require("../../../utils/config");

Page({
  data: {
    artwork: {}, // 初始化数据
    showFullDescription: false, // 是否显示完整描述
    truncatedDescription: "", // 截断的描述
  },
  onLoad(options) {
    /// 显示分享菜单，包括分享到朋友圈
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"], // 同时支持分享给好友和朋友圈
      success() {
        console.log("分享菜单已显示");
      },
      fail(err) {
        console.error("分享菜单显示失败:", err);
      },
    });
    // 获取屏幕宽度
    const systemInfo = wx.getWindowInfo();
    this.setData({ screenWidth: systemInfo.screenWidth });
    // options 中包含了 URL 的查询参数
    const artWorkId = options.artWorkId;
    console.log("接收到的艺术画 ID 为:", artWorkId);

    // 使用 artWorkId 来获取艺术作品的详细信息
    // 例如，发起网络请求获取数据
    this.getArtworkDetails(artWorkId);
  },
  async getArtworkDetails(artWorkId) {
    const response = await getArtworkDetailsById(artWorkId);
    if (response.code === "00000") {
      const artwork = response.data;
  
      // 拼接图片路径
      artwork.primaryImageSmallUrl = `${config.ImageURL}${artwork.primaryImageSmallUrl}`;
      console.log("拼接后的图片路径:", artwork.primaryImageSmallUrl);
  

      // 处理description，将<p>替换为<div class="paragraph">
      if (artwork.description) {
        artwork.description = this.replacePTags(artwork.description);
      }

      // 确保 description 有值，否则设置为 ""
      const truncatedDescription = artwork.description && artwork.description.trim() !== "" 
        ? artwork.description.slice(0, 300)
        : "";
      this.setData({ artwork, truncatedDescription });
      console.log("艺术作品的描述信息：" + truncatedDescription);
      this.saveToHistory(artwork); // 记录到历史
    } else {
      wx.showToast({ title: "加载失败", icon: "error" });
    }
  },

  // 将<p>标签替换为<div class="paragraph">
  replacePTags: function (html) {
    return html
        .replace(/<p>/g, '<div class="paragraph">') // 替换<p>为<view class="paragraph">
        .replace(/<\/p>/g, '</div>'); // 替换</p>为</view>
  },

  // 切换传记展开/收起状态
  toggleBiography: function () {
    this.setData({
      showFullDescription: !this.data.showFullDescription,
    });
  },

  // 记录到历史
  saveToHistory(artwork) {
    let history = wx.getStorageSync("historyArtworks") || [];
    // 检查是否已存在
    const exists = history.some((item) => item.id === artwork.id);
    if (!exists) {
      history.unshift(artwork); // 新记录放在前面
      if (history.length > 50) history.pop(); // 限制历史记录最多 50 条
      wx.setStorageSync("historyArtworks", history);
    }
  },

  /* async getArtworkDetails(artWorkId){
    const response = await getArtworkDetailsById(artWorkId);
    if (response.code === "00000") {
      const artwork = response.data;

      //拼接图片路径
      artwork.primaryImageSmallUrl = `${config.ImageURL}${artwork.primaryImageSmallUrl}`;
      console.log("拼接后的图片路径:", artwork.primaryImageSmallUrl);

      // 计算图片高度
      this.calculateImageHeight(artwork.primaryImageSmallUrl).then((height) => {
        artwork.height = height; // 动态添加 height 属性
        // 确保 description 有值，否则设置为 ""
        const truncatedDescription = artwork.description && artwork.description.trim() !== "" 
        ? artwork.description.slice(0, 300)
        : "";
        this.setData({ artwork, truncatedDescription });
      });
    } else {
      wx.showToast({ title: "加载失败", icon: "error" });
    }
  }, */
  /* async calculateImageHeight(imageUrl) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: imageUrl,
        success: (res) => {
          const aspectRatio = res.width / res.height; // 获取宽高比
          const height = this.data.screenWidth / aspectRatio + 150; // 根据屏幕宽度计算高度
          resolve(height);
        },
        fail: (err) => {
          console.error("获取图片信息失败:", err);
          reject(err);
        },
      });
    });
  }, */
  previewImage() {
    const imageUrl = this.data.artwork.primaryImageSmallUrl;

    // 调用 wx.previewImage 显示图片
    wx.previewImage({
      current: imageUrl, // 当前显示的图片
      urls: [imageUrl], // 可预览的图片列表
    });
  },
  toggleDescription() {
    console.log("正在调用toggleDescription()方法")
    this.setData({
      showFullDescription: !this.data.showFullDescription,
    });
  },
  navigateToArtist(e) {
    const id = e.currentTarget.dataset.id;
    console.log("跳转到艺术家id："+ id + "详细页面")
    wx.navigateTo({ url: `/pages/artist/detail/detail?id=${id}` });
  },
  navigateToCategory(e) {
    const id = e.currentTarget.dataset.id;
    console.log("跳转到类别id："+ id + "详细页面")
    wx.navigateTo({ url: `/pages/category/detail/detail?id=${id}` });
  },
  navigateToMovement(e) {
    const id = e.currentTarget.dataset.id;
    console.log("跳转到流派id："+ id + "详细页面")
    wx.navigateTo({ url: `/pages/movement/detail/detail?id=${id}` });
  },
  navigateToTopic(e) {
    const id = e.currentTarget.dataset.id;
    console.log("跳转到话题id："+ id + "详细页面")
    wx.navigateTo({ url: `/pages/topic/detail/detail?id=${id}` });
  },
  toggleLike() {
    const isLiked = this.data.artwork.isLiked;
    this.setData({ "artwork.isLiked": !isLiked });
    const params = {
      artWorkId: this.data.artwork.id,
      isLiked: !isLiked,
    };
    //发送请求修改用户的喜好状态
    updateUserLikeStatus(params);
    // wx.showToast({ title: "切换喜欢的状态", icon: "success" });
  },
  onDownload() {
    const imageUrl = this.data.artwork.primaryImageUrl;
    wx.showLoading({ title: "下载中..." }); // 显示加载提示
    console.log("下载的图片URL：" + imageUrl);
  
    wx.downloadFile({
      url: imageUrl, // 图片 URL
      success: (res) => {
        if (res.statusCode === 200) {
          // 下载成功，尝试保存到相册
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              //发送请求，记录用户下载的行为，该艺术画作品的下载量+1
              downloadArtwork(this.data.artwork.id);
              wx.showToast({ title: "图片保存成功", icon: "success" });
            },
            fail: (err) => {
              console.error("保存图片失败:", err);
              if (err.errMsg.includes("auth deny") || err.errMsg.includes("auth denied")) {
                // 如果用户拒绝授权，提示并引导用户到设置中开启授权
                wx.showModal({
                  title: "授权提示",
                  content: "保存图片需要您授权访问相册，是否前往设置开启权限？",
                  cancelText: "取消",
                  confirmText: "去授权",
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      wx.openSetting({
                        success: (settingRes) => {
                          if (settingRes.authSetting["scope.writePhotosAlbum"]) {
                            // 用户重新授权后再尝试保存
                            wx.saveImageToPhotosAlbum({
                              filePath: res.tempFilePath,
                              success: () => {
                                //发送请求，记录用户下载的行为，该艺术画作品的下载量+1
                                downloadArtwork(this.data.artwork.id);
                                wx.showToast({ title: "保存成功", icon: "success" });
                              },
                              fail: (saveErr) => {
                                console.error("重新保存图片失败:", saveErr);
                                wx.showToast({ title: "保存失败", icon: "error" });
                              },
                            });
                          } else {
                            wx.showToast({ title: "未授权成功", icon: "error" });
                          }
                        },
                        fail: (openErr) => {
                          console.error("打开设置失败:", openErr);
                          wx.showToast({ title: "设置打开失败", icon: "error" });
                        },
                      });
                    } else {
                      wx.showToast({ title: "保存已取消", icon: "none" });
                    }
                  },
                });
              } else {
                wx.showToast({ title: "保存失败", icon: "error" });
              }
            },
          });
        } else {
          // 状态码不是 200，说明下载失败
          console.error("下载失败，状态码：", res.statusCode);
          if (res.statusCode === 403) {
            wx.showModal({
              title: "下载失败",
              content: "访问资源被禁止（403）。请检查是否需要登录或确认URL是否可访问。",
              showCancel: false,
              confirmText: "确定",
            });
          } else {
            wx.showToast({
              title: `下载失败: ${res.statusCode}`,
              icon: "error",
            });
          }
        }
      },
      fail: (err) => {
        // 下载失败，打印错误信息
        console.error("下载失败：", err);
        let errorMessage = "下载失败";
        if (err.errMsg.includes("timeout")) {
          errorMessage = "下载超时";
        } else if (err.errMsg.includes("403")) {
          errorMessage = "权限不足，无法下载";
        } else if (err.errMsg.includes("404")) {
          errorMessage = "文件未找到";
        }
        wx.showToast({ title: errorMessage, icon: "error" });
      },
      complete: () => {
        wx.hideLoading(); // 隐藏加载提示
      },
    });
  },
  onShareAppMessage() {
    // 分享到朋友
    console.log("用户选择分享到朋友");
    const artworkId = this.data.artwork.id;
  
    if (!artworkId) {
      console.error("未能获取到艺术画作品的 ID");
      return;
    }
    //发送请求，记录用户分享的行为，该艺术画作品的分享量+1
    //此时无法保证用户是否成功分享，存在一定的误差
    shareArtwork(artworkId).then(() => {
      console.log("分享行为已记录");
    }).catch(err => {
      console.error("记录分享行为失败：", err);
    });
    return {
      title: `看看这个艺术品: ${this.data.artwork.title}`,
      path: `/pages/artwork/detail?artWorkId=${this.data.artwork.id}`, // 分享路径
      imageUrl: this.data.artwork.primaryImageUrl, // 分享封面图
      success: () => {
        console.log("用户分享完成");
        // 在这里记录用户的分享行为，比如发送到服务器
        // this.recordShareAction();
      },
      fail: (err) => {
        console.error("分享失败或取消：", err);
      },
    };
  },
  onShareTimeline() {
    // 分享到朋友圈
    console.log("用户选择分享到朋友圈");
    //发送请求，记录用户分享的行为，该艺术画作品的分享量+1
    //此时无法保证用户是否成功分享，存在一定的误差
    shareArtwork(this.data.artwork.id)
    return {
      title: `看看这个艺术品: ${this.data.artwork.title}`,
      path: `/pages/artwork/detail?artWorkId=${this.data.artwork.id}`, // 分享路径
      imageUrl: this.data.artwork.primaryImageUrl, // 分享封面图
      success: () => {
        console.log("用户分享完成");
        // 在这里记录用户的分享行为，比如发送到服务器
        // this.recordShareAction();
      },
      fail: (err) => {
        console.error("分享失败或取消：", err);
      },
    };
  },
  onShare() {
    wx.showToast({
      title: "请点击右上角菜单进行分享",
      icon: "none",
    });
  },
});
